import config from 'config.js';
import Api from './api.js';
import util from './util.js';
var tocken_title = '网络连接失败，请重试！';

// 判断是否授权
function authorOrNot(app) {
  var that = this;
  var MemberID = wx.getStorageSync('MemberID');
  if (MemberID == null || MemberID == "") {
    // 微信授权登录
    wx.redirectTo({
      url: '/pages/welcome/welcome'
    });
    return false;
  }
};

// 微信授权
function wxLogin(app, IsNew) {
  wx.login({
    success: function(res) {
      if (res.code) {
        var code = res.code;
        wx.getUserInfo({
          success: function(res) {
            var username = res.userInfo.nickName
            var img = res.userInfo.avatarUrl;
            // 请求自己服务器
            Login(app, code, username, img, IsNew);
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '获取用户登录失败！' + res.errMsg
        })
      }
    },
  })
};

function Login(app, code, username, img, IsNew) {
  var that = this;
  var params = {
    code: code
  };
  Api.getPromise(config.WXAuth, params).then(data => {
    if (data.StatusCode != "n") {
      var OpenID = data.PayLoad.OpenID;
      wx.setStorageSync('OpenID', OpenID);
      var params = {
        HeadPhoto: img,
        OpenID: OpenID,
        NickName: encodeURIComponent(username),
        Flag: app.globalData.Flag
      }
      console.log("params:" + JSON.stringify(params))
      return Api.postPromise(config.MemberAuth, params)
    } else {
      wx.showToast({
        title: "获取OpenID失败"
      });
    }
  }).then(data => {
    if (data.StatusCode != "n") {
      var MemberID = data.PayLoad.MemberID;
      wx.setStorageSync('MemberID', MemberID);
      // 此处做判断是否 已注册身份
      return MemberID;
    } else {
      //获取失败
      wx.showToast({
        title: "保存用户信息失败"
      });
    }
  }).then(data => {
    return Api.getPromise(config.MemberIdentity, {
      memberid: data
    });
  }).then(data => {
    wx.hideLoading();
    if (data.StatusCode != "n" && data.PayLoad != null && IsNew != 'new') {
      app.globalData.MemberIdentity = data.PayLoad;
      if (data.PayLoad.length == 1) {
        wx.switchTab({
          url: '/pages/index/index',
        });
        app.globalData.Flag = data.PayLoad[0].ID;
        app.globalData.Member = data.PayLoad[0];
        app.globalData.ClassID = data.PayLoad[0].ClassID;
      } else if (data.PayLoad.length > 1) {
        wx.reLaunch({
          url: '/pages/guide/switchClass',
        });
      }
    } else {
      //授权成功后， 跳转进入页
      wx.navigateTo({
        url: app.globalData.currPage
      });
    }
  }).catch(e => {
    wx.showToast({
      title: "请求数据异常"
    });
  });
}

module.exports = {
  wxLogin: wxLogin,
  authorOrNot: authorOrNot,
}